<?php

/**
 * MVM_MALL 网上商店系统  购物车
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * $Author:  www.mvmmall.com  $
 * $Date: 2008-07-02 $
 * $Id: cart.class.php  www.mvmmall.com$
 * ---------------------------------------------
*/

Class cart
{
	var  $total_count;
	var  $total_price;
	var  $total_point ;
	var  $total_kg;
	/**
     * 
     * 类的构造函数，使购物车保持稳定的初始化状态 
     * @access  public 
     * @return  void   无返回值
     * @param   void   无参数
     */
   function __construct()
	{
		$this->total_count = 0;
		$this->total_price = 0;
		$this->total_point = 0;
		
	}
	function cart()
	{
		$this->total_count = 0;
		$this->total_price = 0;
		$this->total_point = 0;
	}	
    /**
     * 增加商品到当前购物车
     * @access public
     * @param  int $goods_id  商品uid
     * @param  int $ps_num    商品数量
     * @param  int $ps_select 商品类型，1为收藏，0为购买
     * @param array $att_value  商品属性列表值
     */
   function add ($goods_id,$ps_num,$ps_select,$att_value){
   	global $db,$tablepre,$m_check_id,$m_check_cart,$m_now_time;
   	$goods_id     = (int)$goods_id;
   	$ps_num       = (int)$ps_num;
   	$ps_num==0    && exit;
   	//1为收藏，0为购买
   	if($ps_select == 'S') {
   		$ps_wish = '1';
   		!$m_check_id && show_msg('wish_login_id'); //判断是否登陆
   	} else {
   		$ps_wish = '0';
   	}
   	$goods_rt    = $db->get_one("SELECT uid,cart_sess,cart_goods_id,cart_num,goods_att FROM `{$tablepre}cart_table` WHERE cart_sess = '$m_check_cart' AND cart_goods_id = '$goods_id'");
   	//属性价格
   	$enprice = 0.00;
   	if(is_array($att_value)){
   	    $goods_att           = '';
   	    foreach ($att_value as $key=>$val){
   	        $val             = (int)$val;
   	        $att_list        = $db->get_one("SELECT a.*,b.id,b.att_name FROM `{$tablepre}att_value` a LEFT JOIN `{$tablepre}attribute` b ON a.bute_id=b.id WHERE a.att_id='$val'");
   	        $enprice         +=$att_list['att_price'];
   	        $goods_att       .= "$att_list[att_name]:$att_list[att_value]($att_list[att_price])  ";
   	    }
   	    $goods_att           =  dhtmlchars($goods_att);
   	}else {
   	    $goods_att           = false;
   	}
   	//判断是否已经有该商品了
   	if($goods_rt['uid'] && $goods_rt['goods_att']==$goods_att) {
   		//!goods_stock_check($goods_id,$ps_num+$goods_rt['cart_num']) && show_msg('sale_num');
   		///$db->query("UPDATE `{$tablepre}cart_table` SET cart_num = cart_num + '$ps_num' WHERE uid = '$goods_rt[uid]'");
        return $goods_rt['uid'];
   	} else {
   		unset($goods_rt);
   		$goods_rt = $db->get_one("SELECT uid,goods_name FROM `{$tablepre}goods_table` WHERE uid = '$goods_id'");
   		$goods_rt == false && show_msg('db_avess');
   		!goods_stock_check($goods_id,$ps_num) && show_msg('sale_num');
   		$price    = $this->get_price($goods_id,$ps_num)+ $enprice;//商品价格+属性价格
   		$goods_rt['goods_name']        = addslashes($goods_rt['goods_name']);
   		$query = "INSERT INTO `{$tablepre}cart_table` SET
	                cart_wish          = '$ps_wish',
					cart_id            = '$m_check_id',
                    cart_goods_id      = '$goods_rt[uid]',
                    cart_sess          = '$m_check_cart',
                    cart_subject       = '$goods_rt[goods_name]',
                    cart_price         = '$price',
                    goods_att          = '$goods_att',
                    cart_num           = '$ps_num',
                    cart_type          = '0',
                    register_date      = '$m_now_time'
                     ";
   		$db->query($query);
   		return $db->insert_id();
   	}
   }
   
   /**
     * 批量改变购物车数量
     * @access public
     * @param  array $cart_list_num  购买的数量
     * @param  array $cart_uid  商品ID
     */
   function change($cart_list_num,$cart_uid)
   {
   	global $db,$tablepre,$m_check_id;
   	for ($i=0;$i<count($cart_list_num);$i++) {
   		$uid      = (int)$cart_uid[$i];
   		$nums     = (int)$cart_list_num[$i];
   		$nums <=0 && $this->delete($cart_uid[$i]);
   		$sql = $m_check_id ? "SELECT uid,cart_type,cart_goods_id,goods_att,cart_num FROM `{$tablepre}cart_table` WHERE cart_id='$m_check_id' AND uid = '$uid'" : "SELECT uid,cart_type,cart_goods_id,goods_att,cart_num,cart_sess FROM `{$tablepre}cart_table` WHERE cart_sess = '$m_check_cart' OR cart_type='0' AND uid = '$uid'";
   		$goods_rt = $db->get_one($sql);
   		if($goods_rt['uid'] && $goods_rt['cart_type']=='0' && $cart_list_num[$i]!=$goods_att['cart_num']){
   			!goods_stock_check($goods_rt['cart_goods_id'],$nums) && show_msg('sale_num');
   			//更新数据库内容
   			$db->query("UPDATE `{$tablepre}cart_table` SET cart_num ='$nums' WHERE uid = '$goods_rt[uid]'");
   		}
   	}
   }
   
   
   /**
     * 删除购物车商品
     * @access public
     * @param  int 商品ID
     */
      function delete($id)
      {
      	global $m_check_id,$db,$tablepre,$m_check_cart;
      	if($m_check_id){
      		if ($id==0) {
      			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_id = '$m_check_id' AND cart_wish = '0'");//为0，清空购物车
      		}else {
      			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_id='$m_check_id'  AND uid = '$id'");
      			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_sess='$m_check_cart' AND uid = '$id'");
      		}
      	} else {
      		if ($id==0) {
      			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_sess = '$m_check_cart' AND cart_wish = '0'");//为0，清空购物车
      		} else {
      			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_sess='$m_check_cart' AND uid = '$id'");

      		}
      	}
      }
      
     /**
     * 改变商品保存属性
     * @access public
     * @param  arr $act  参数，cart 移到购物车上，wish改为收藏状态
     * @param  array $ps_caid  商品ID
     */
     function move($act,$ps_caid)
     {
     	global $db,$tablepre,$m_check_id,$m_check_cart;
     	$arr = $act=='wish' ? 1:0;
     	if (is_numeric($ps_caid) && $ps_caid>0 ){
     		$cart_list = $db->get_one("SELECT uid,cart_subject,cart_num,cart_price FROM `{$tablepre}cart_table` WHERE cart_id = '$m_check_id' AND uid = '$ps_caid'");
     		$cart_list == false && show_msg('wish_disorder');
     	    $db->query("UPDATE `{$tablepre}cart_table` SET cart_wish = '$arr' ,cart_id = '$m_check_id' WHERE uid = '$cart_list[uid]'");
     	} else {
     		show_msg('wish_num_eror');
     	}
     }
     
     
   /**
     * 购物车列表，包含收藏的商品
     * @access public
     * @return  array   2个2维数组
     */
   function cart_list()
   {
   	global $m_check_id,$tablepre,$db,$m_check_cart;
   	if($m_check_id) {
   		$sql = "SELECT a.*,b.goods_file1,b.uid AS goods_id,b.goods_kg,b.goods_point,b.goods_sale_price FROM `{$tablepre}cart_table` a LEFT JOIN `{$tablepre}goods_table` b ON a.cart_goods_id=b.uid WHERE   a.cart_id = '$m_check_id' OR (a.cart_id = '$m_check_id' AND a.cart_type='3') OR (a.cart_sess = '$m_check_cart' AND a.cart_type='0') OR (a.cart_sess = '$m_check_cart' AND a.cart_type='3') ORDER BY a.uid ASC ";
   	}else {
   		$sql = "SELECT a.*,b.goods_file1,b.uid AS goods_id,b.goods_kg,b.goods_point,b.goods_sale_price  FROM `{$tablepre}cart_table` a LEFT JOIN `{$tablepre}goods_table` b ON a.cart_goods_id=b.uid WHERE a.cart_sess = '$m_check_cart'  OR (a.cart_sess = '$m_check_cart' AND a.cart_type='3') ORDER BY a.uid ASC ";
   	}
   	$cart_goods=array();
   	$wish_goods= array();
   	$result = $db->query($sql);
   	while($rt =$db->fetch_array($result)) {
   		$rt['total_price']    = currency($rt['cart_price'] * $rt['cart_num']);
   		$rt['total_kg']       = $rt['goods_kg'] * $rt['cart_num'];//计算总量
   		$rt['photo']          = $rt['goods_file1'];
   		$rt['url']            =  GetBaseUrl('product',$rt['cart_goods_id']);
   		$rt['del_url']        = "cart.php?action=delete&id=$rt[uid]&referer=cart.php?action=list";
   		$rt['subject']        = cut_str($rt['cart_subject'],24);
   		$rt['title']          = $rt['cart_subject'];
   		$rt['price']          = currency($rt['cart_price']);
   		$rt['point']          = $rt['goods_point'];
   		$rt['kg']             = $rt['goods_kg'];
   		$rt['cart_type']=='3' && $rt['disabled']='disabled';
   		if($rt['cart_wish']==0){
   			$total_price     +=($rt['cart_price'] * $rt['cart_num']);
   			$total_kg        +=($rt['goods_kg'] * $rt['cart_num']);
   			$total_point     += $rt['goods_point'] * $rt['cart_num'];
   			$cart_nums       +=$rt['cart_num'];
   			$cart_goods[]     = $rt;
   		} else{
   			$wish_goods[]     = $rt;
   		}
   	}
   	unset($rt);
   	$cart_rt[0]        = $cart_goods;
   	$cart_rt[1]        = $wish_goods;
   	$this->total_kg    = $total_kg;
    $this->total_point = $total_point;
   	$this->total_price = $total_price;
   	$this->total_count = $cart_nums;
   	return $cart_rt;
   }
   
   /**
     * 
     * 优惠购买函数 
     * @access  public 
     * @return  void   无返回值
     * @param   void   无参数
     */
   function privilege($act_id)
   {
   	global $db,$tablepre,$m_check_cart;
   	$act_id      = (int)$act_id;
   	//判断是否已经购买了
   	$order_info  = $db->get_one("SELECT cart_sess,cart_type FROM `{$tablepre}cart_table` WHERE cart_sess = '$m_check_cart' AND cart_type='3'");
   	$order_info['cart_type'] && show_msg('buy_one','cart.php?action=list');;
   	//读取优惠活动商品价格信息
   	$act_info    = $db->get_one("SELECT a.*,b.uid,b.goods_file1,b.goods_name FROM `{$tablepre}activity` a LEFT JOIN `{$tablepre}goods_table` b ON a.goods_id=b.uid WHERE a.act_type='3' AND a.act_id='$act_id'");
   	$act_config  = unserialize($act_info[act_config]);
   	//判断定金额是否达到优惠条件
   	$result      = $db->query("SELECT cart_price,cart_num FROM {$tablepre}cart_table WHERE cart_sess = '$m_check_cart'");
   	$order_price = 0.00;
   	while ($rt = $db->fetch_array($result)){
   		$order_price += ($rt['cart_num']*$rt['cart_price']);
   	}
   	if ($order_price<$act_config['start_price'] || $order_price>$act_config['end_price']){
   		show_msg('buy_pirce_err','cart.php?action=list');;
   	}
   	//写入定单
   	$query = "INSERT INTO `{$tablepre}cart_table` SET
	                cart_wish          = '0',
					cart_id            = '$m_check_id',
                    cart_goods_id      = '$act_info[uid]',
                    cart_sess          = '$m_check_cart',
                    cart_subject       = '$act_info[goods_name]',
                    cart_price         = '$act_config[buy_price]',
                    cart_num           = '1',
                    cart_type          = '3',
                    register_date      = '$m_now_time'
                     ";
   	$db->query($query);

   }
	
   
   /**
     * 商品销售价格
     * @access private
     * @param  int $goods_id  商品ID
     * @param  int $buy_nums  商品数量
     * @return  float   返回值商品价格
     */
   function get_price($goods_id,$buy_nums=1)
   {
   	global $db,$tablepre,$m_now_time,$mm_group_id;
   	//批发价格
   	$who_rt              = $db->get_one("SELECT * FROM `{$tablepre}wholesale` WHERE goods_id='$goods_id' AND enabled='1'");
   	$who_rt['rank_list'] = explode(',',$who_rt['rank_list']);
   	$who_list            = unserialize($who_rt['price']);
   	if (in_array($mm_group_id,$who_rt['rank_list'])){
   		foreach ($who_list as $val){
   			$buy_nums>=$val['nums'] && $price[] = $val['price'];
   		}
   		$price   = min($price);
   		if($price) return $price;
   	}
   	//end
   	$product = $db->get_one("SELECT uid,goods_sale_price,goods_class,end_date,event_price,price_sale FROM `{$tablepre}goods_table` WHERE uid='$goods_id'");
   	if($product['goods_class']=='1'&& $product['end_date'] >$m_now_time){
   		$price = $product['event_price'];
   		return $price;
   	}
   	$group_id = (int)$mm_group_id;
   	if(empty($group_id)){
   		return $product['goods_sale_price'];
   	}
   	if($product['price_sale']==2) {
   		$list = $db->get_one("SELECT a.*,b.group_id FROM `{$tablepre}enprice` a LEFT JOIN `{$tablepre}grade_table` b ON a.group_id=b.group_id  WHERE a.goods_id='$product[uid]' AND a.group_id='$group_id'");
   		$price = $list['price'];

   	} else {
   		$list =  $db->get_one("SELECT group_name,degree,discount,group_id FROM `{$tablepre}grade_table` WHERE  group_id='$group_id'");
   		$price= $list['discount'] ? $list['discount']*$product['goods_sale_price']/100 : $product['goods_sale_price'];
   	}
   	return $price;
   }
}